import json
import os
import csv
from filelock import FileLock

progress_data = {"brand_series": 0, "series_model": 0, "model_config": 0}


# 新增函数，用于保存当前处理的进度
def load_progress(progress_file):
    global progress_data  # 声明 progress_data 为全局变量

    if os.path.exists(progress_file):
        with open(progress_file, 'r') as file:
            progress_content = file.read().strip()
            if progress_content:
                progress_data = json.loads(progress_content)


def save_progress(progress_file, key, line_num):
    global progress_data

    load_progress("data/progress.txt")
    lock_path = "data/progress_file.lock"
    lock = FileLock(lock_path, timeout=1)

    # 避免并发写文件
    with lock:
        progress_data[key] = line_num
        with open(progress_file, 'w') as file:
            file.write(json.dumps(progress_data))


# 该函数用于删除一个子CSV文件中与父CSV文件中，位点文件指向行的key字段，匹配的所有行
def delete_matching_rows(son_csv_path, parent_csv_path, key, index):
    global progress_data

    # 首先，确定parent csv在位点文件中指向的行
    with open(parent_csv_path, 'r') as parent_file:
        reader = csv.reader(parent_file)
        rows = list(reader)
        parent_row = rows[progress_data[key]]

    # 接下来，删除son csv中index列与parent_row[index]匹配的行
    with open(son_csv_path, 'r') as model_file:
        reader = csv.reader(model_file)
        son_rows = list(reader)

    # 先判断有没不匹配的没有的话，如果有的话，直接返回
    son_to_delete = [son_row for son_row in son_rows if son_row[index] == parent_row[index]]

    if len(son_to_delete) > 0:
        son_to_keep = [son_row for son_row in son_rows if son_row[index] != parent_row[index]]
        with open(son_csv_path, 'w', newline='') as son_file:
            writer = csv.writer(son_file)
            writer.writerows(son_to_keep)


# Expose progress_data to be accessed by other modules
def get_progress_data():
    global progress_data
    return progress_data


# Allow other modules to update progress_data
def update_progress_data(key, value):
    global progress_data
    progress_data[key] = value
